package cn.edu.zjicm.wordsnet_d.view;

import java.math.BigDecimal;
import java.text.DecimalFormat;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.TextView;

public class RiseNumTextView extends TextView{
	// 递减/递增 的变量值
	private double mRate;
	// view 设置的值
	private double mValue;
	// 当前显示的值
	private double mCurValue;
	// 当前变化后最终状态的目标值
	private double mGalValue;
	// 控制加减法
	private int rate = 1;
	// 当前变化状态(增/减/不变)
	private int mState = 0;
	private boolean refreshing;
	private static final int REFRESH = 1;
	DecimalFormat fnum = new DecimalFormat("0");
	OnRiseCompleteListener onRiseCompleteListener;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {

			case REFRESH:
				if (rate * mCurValue < mGalValue) {
					refreshing = true;
					setText(fnum.format(mCurValue));
					mCurValue += mRate * rate;
					mHandler.sendEmptyMessageDelayed(REFRESH, 30);
				} else {
					setText(fnum.format(mGalValue));
					onRiseCompleteListener.onRiseCompleted();
				}
				break;
			}
		};
	};

	public RiseNumTextView(Context context) {
		super(context);
	}

	public RiseNumTextView(Context context, AttributeSet set) {
		super(context, set);
	}

	public RiseNumTextView(Context context, AttributeSet set, int defStyle) {
		super(context, set, defStyle);
	}

	public void setValue(double value,OnRiseCompleteListener onRiseCompleteListener) {
        mCurValue = 0;
        mGalValue = value;
        mValue = value;
        mRate = (double) (mValue / 20);
        BigDecimal b = new BigDecimal(mRate);
        mRate = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        this.onRiseCompleteListener = onRiseCompleteListener;
    }
	
	public void startRise(){
		mHandler.sendEmptyMessage(REFRESH);
	}

}

